﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Input;

namespace GMUtilitiesDotNet.Helpers
{
    public static class UIHelpers
    {
        #region Methods
        public static T FindVisualCurrentOrParent<T>(DependencyObject pObject) where T : DependencyObject
        {
            T current = pObject as T;
            if (current != null)
            {
                return current;
            }
            else
            {
                return FindVisualParent<T>(pObject);
            }
        }

        public static T FindVisualParent<T>(DependencyObject pObject) where T : DependencyObject
        {
            // get parent item
            DependencyObject parentObject = VisualTreeHelper.GetParent(pObject);

            // we've reached the end of the tree
            if (parentObject == null) return null;

            // check if the parent matches the type we're looking for
            T parent = parentObject as T;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                // use recursion to proceed with next level
                return FindVisualParent<T>(parentObject);
            }
        }

        public static Point GetNormalizedPosition(MouseEventArgs pArgs, FrameworkElement pView)
        {
            if (pView != null && pView.ActualWidth >= 1.0 && pView.ActualHeight >= 1.0)
            {
                Point viewPoint = pArgs.GetPosition(pView);
                Point normalizedViewportPoint = new Point(
                    viewPoint.X / pView.ActualWidth,
                    viewPoint.Y / pView.ActualHeight);

                return normalizedViewportPoint;
            }
            else
            {
                return new Point();
            }
        }

        public static Point GetNormalizedPosition(MouseEventArgs pArgs)
        {
            FrameworkElement view = pArgs.Source as FrameworkElement;
            return GetNormalizedPosition(pArgs, view);
        }
        #endregion
    }
}